<template>
  <div class="container">
    <!-- 导航栏 -->
    <nav class="nav-bar login" style="height: 100px;">
      <div class="serial-number" style="padding-top: 40px;">
        身份证 <input placeholder="431333113331113311" size="100" v-model="userId">
        <el-button type="primary" :icon="Search" @click="loaduserId">加载身份证号码</el-button>
        <el-button type="warning" :icon="Search" @click="loadpatient">加载患者信息</el-button>
      </div>
    </nav>
    <el-divider />
    <!-- 表格导航 -->
    <div class="table-nav login">
      <el-row>
        <el-col :span="24">
          <div class="idcard-section ">
            <span style="color: red;">*</span>身份证号码
            <el-input v-model="formData.idCard" placeholder="输入身份证18位" style="width: 200px" maxlength="18"
                      class="margin-radio" required/>
            <span style="color: red;" class="margin-radio">*</span>患者信息
            <el-input v-model="formData.name" placeholder="孙子" style="width: 200px" maxlength="20"
                      class="margin-radio" />
            <span style="color: red;">*</span>患者电话
            <el-input v-model="formData.phone" placeholder="12345678" style="width: 200px" maxlength="11"
                      class="margin-radio" />
            <span class="margin-radio">
              <input type="radio" v-model="formData.sex" value="0"> 男
              <input type="radio" v-model="formData.sex" value="1"> 女
              <input type="radio" v-model="formData.sex" value="2"> 未知
            </span>
            出生日期
            <input type="date" class="margin-radio" v-model="formData.birthday" @change="setAge()">
            <span style="color: red;">*</span>患者年龄
            <el-input v-model="formData.partialage" placeholder="年龄" style="width: 200px" maxlength="20"
                      class="margin-radio" />
          </div>
          <div class="idcard-section">
            <span style="color: red;">*</span>地址信息
            <el-input v-model="formData.address" placeholder="患者地址信息" style="width: 200px" maxlength="20" />
          </div>
        </el-col>
      </el-row>
    </div>
    <el-divider />
    <!-- 用户信息 -->
    <div class="user-auth">
      <div class="clinic-selector">
        <el-radio-group v-model="selectedOption" size="small" class="compact-radio-group">
          <el-radio-button v-for="option in options" :key="option.regItemId" :label="option.regItemName"
                           class="custom-option"
                           @change="changeoption(option.regItemId,option.regItemName,option.regItemFee)">
            {{ option.regItemName }}
          </el-radio-button>
        </el-radio-group>
      </div>
      <div class="clinic-selector2" style="padding-left: 50%;">
        挂号费：<span text="">{{ hisSchedulingMoery }}</span>￥
        <el-button type="danger" :iconhisSchedulingMoery="Search" @click="RegisteredFeesApply()">挂号收费</el-button>
      </div>
    </div>
    <el-divider />
    <!-- 用户列表 -->
    <el-form :inline="true" :model="filterForm" class="demo-form-inline">
      <el-form-item label="所属科室">
        <el-select v-model="value2" placeholder="请选择科室" size="large" style="width: 240px" clearable>
          <el-option v-for="item in options2" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="挂号时段">
        <el-select v-model="value3" placeholder="挂号时段" size="large" style="width: 240px" clearable>
          <el-option v-for="item in timePeriod" :key="item.dict_value" :label="item.dict_label"
                     :value="item.dict_value" />
        </el-select>
      </el-form-item>
      <el-form-item label="挂号类型">
        <el-select clearable v-model="value4" placeholder="Select" size="large" style="width: 240px">
          <el-option v-for="item in subsectionType" :key="item.dict_value" :label="item.dict_label"
                     :value="item.dict_value" />
        </el-select>
      </el-form-item>
      <el-form-item label="挂号时间">
        <el-date-picker v-model="date2" type="datetime-local" placeholder="Select date and time"
                        :shortcuts="shortcuts" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 科室信息 -->
    <el-table :data="departmentData" border
              style="width: 100%"
              @row-click="handleRowClick"
              :highlight-current-row="true"
              :row-class-name="getRowClassName">
      <el-table-column prop="deptId" label="科室ID" />
      <el-table-column prop="deptName" label="科室名称" />
      <el-table-column prop="schedulingNumber" label="当前号码" />
    </el-table>
    <!-- 显示选中行信息 -->
    <div v-if="selectedRowInfo">
      <h3>选中行信息</h3>
      <p>科室 ID: {{ selectedRowInfo.deptId }}</p>
      <p>科室名称: {{ selectedRowInfo.deptName }}</p>
      <p>当前号码: {{ selectedRowInfo.schedulingNumber }}</p>
    </div>
    <!-- 分页 -->
    <div class="pagination">
      <span>共2条</span>
      <el-select v-model="PageSize" size="mini">
        <el-option :value="10" label="10条/页" />
        <el-option :value="20" label="20条/页" />
      </el-select>
      <el-pagination :current-page="currentPage" :page-size="pageSize" layout="prev, pager, next" :total=total />
      <el-input-number v-model="jumpPage" :min="1" size="mini" />
      <el-button size="mini">前往</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { formatDate } from '@/utils/dateFormatter';//引入全局日期格式化工具
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/http'
import { h } from 'vue'
//总条数
let total = ref('')
const renameForm = reactive({
  name: '',
  address: '',
  gender: '未填',
  birthDate: ''
})
let form = ref({
  sex: '',
  status: '0'
})
//
//门诊双向绑定
let hisSchedulingMoery = ref('')
let hisSchedulin=ref('')
//
function changeoption(id, vl, moery) {
  console.log(vl+"AAA")
  console.log(moery)
  hisSchedulin.value=id;
  hisSchedulingMoery.value = moery;
  //调用查询所有科室的方法
    // 将格式化后的日期时间赋值给 ref 变量
    if (value2.value === undefined) {
    value2.value = ''
  }
  if (value3.value === undefined) {
    value3.value = ''
  }
  if (value4.value === undefined) {
    value4.value = ''
  }
  if(id==2 ||id==1){
    hisSchedulin.value="1";
  }
  if(id==3 ||id==4){
    hisSchedulin.value="2";
  }
  //获取表格信息
    getPageDept(PageNum.value, PageSize.value, value2.value, value3.value, value4.value, date2.value,hisSchedulin.value);

}
const tableNavItems = ref(['首页', '搜索', '搜索结果', '搜索功能'])
const authChecked = ref([false, false, false])
//表格属性
let departmentData = ref([])

//时间控件
const date2 = ref('')
//身份证
const partialID = ref('')
const completedID = ref('')

const options = ref([
])
//封装查询挂号费用表
function getHisCareOrderItem() {
  //发送http请求
  http.get("/RegisteredItem/getAll").then((res) => {
    options.value = res
  }).catch(() => {
    console.log("失败")
  })
}
const selectedOption = ref('1')
let PageNum = ref(1)
let PageSize = ref(3)
//挂载完成之获取科室所有信息
onMounted(() => {
  // 获取当前日期和时间
  const now = new Date();
  // 获取年份
  const year = now.getFullYear();
  // 获取月份，注意月份从 0 开始，所以要加 1
  const month = String(now.getMonth() + 1).padStart(2, '0');
  // 获取日期
  const day = String(now.getDate()).padStart(2, '0');
  // 拼接成符合 datetime-local 格式的字符串
  const formattedDateTime = `${year}-${month}-${day}`;
  // 将格式化后的日期时间赋值给 ref 变量
  date2.value = formattedDateTime;
  //获取科室
  getdept();
  //获取挂号费用
  getHisCareOrderItem();
  // 获取挂号时段字典（假设字典类型为his_subsection_type）
  fetchDictData("his_subsection_type");
  fetchDictData2("his_scheduling_type");
  //获取表格信息
  getPageDept(PageNum.value, PageSize.value, value2.value, value3.value, value4.value, date2.value,hisSchedulin.value);
})
function getPageDept(PageNum, PageSize, DeptName, time, type, date,hisSchedulin) {
  
  //发送get请求
  http.get("/dept/getPageDept", {
    params: {
      pageNum: PageNum,
      PageSize: PageSize,
      DeptName: DeptName,
      time: time,
      type: type,
      date: date,
      hisSchedulin:hisSchedulin
    }
  }).then((res) => {
    departmentData.value = res.list
    total.value = res.total
    console.log("departmentData", departmentData.value)
    console.log("成功", res)
  }).catch((res) => {
    console.log("失败")
  })
}
//查询所有部门
function getdept() {
  //发送http请求，获取科室信息
  http.get("/dept/getdept").then((res) => {
    options2.value = res
  }).catch((res) => {
    console.log("失败")
  })
}
//查询字典数据表的条件
// 获取时段类型字典
let timePeriod = ref([])
const fetchDictData = async (dictType) => {
  await http.get('/api/dict/data/' + dictType).then((res) => {
    timePeriod.value = res;
  }).catch((error) => {
    console.error('获取字典数据失败:', error);
  })
};
//类型
let value4 = ref('')
let subsectionType = ref([])
const fetchDictData2 = async (dictType) => {
  await http.get('/api/dict/data/' + dictType).then((res) => {
    subsectionType.value = res;
  }).catch((error) => {
    console.error('获取字典数据失败:', error);
  })
};

//所属科室
// 科室名称：
const name = ref("")
// 科室
const value2 = ref('')
//下拉框默认值
const options2 = ref([
])
// 挂号时段
const value3 = ref('')
//下拉框默认值
const options3 = ref([
])
//双向绑定id
let userId = ref('')

//加载身份证
function loaduserId() {
  //发送http请求
  http.get("/patient/getUserId?idCard=" + userId.value).then((res) => {
    if (res != '') {
      formData.value.idCard = res.idCard; // id
      formData.value.name = res.name; //患者信息
      formData.value.birthday = res.birthday; // 出生时间
      formData.value.sex = res.sex; //性别
      formData.value.phone = res.phone; //患者电话
      formData.value.address = res.address; //患者地址
      formData.value.patientId=res.patientId;//
      // 计算年龄
      setAge();
    }
  });
}
//加载患者信息
function loadpatient() {
  //发送http请求
  http.get("/patient/getUserId?idCard=" + userId.value).then((res) => {
    if (res != '') {
      formData.value.idCard = res.idCard; // id
      formData.value.name = res.name; //患者信息
      formData.value.birthday = res.birthday; // 出生时间
      formData.value.sex = res.sex; //性别
      formData.value.phone = res.phone; //患者电话
      formData.value.address = res.address; //患者地址
      formData.value.patientId=res.patientId;//
      // 计算年龄
      setAge();
    }
  });
}
//查询按钮
function handleSearch() {
  date2.value = formatDate(date2.value, 'YYYY-MM-DD');
  // 将格式化后的日期时间赋值给 ref 变量
  if (value2.value === undefined) {
    value2.value = ''
  }
  if (value3.value === undefined) {
    value3.value = ''
  }
  if (value4.value === undefined) {
    value4.value = ''
  }
  getPageDept(PageNum.value, PageSize.value, value2.value, value3.value, value4.value, date2.value,hisSchedulin.value);
}
// 记录当前选中行的信息
const selectedRowInfo = ref(null);
// 记录当前选中行的索引
const selectedRowIndex = ref(-1);

// 处理行点击事件
const handleRowClick = (row, column, event) => {
  selectedRowInfo.value = row;
  selectedRowIndex.value = departmentData.value.indexOf(row);
};

// 根据行索引返回行的类名
const getRowClassName = ({ row, rowIndex }) => {
  return rowIndex === selectedRowIndex.value ? 'selected-row' : '';
};
//
function RegisteredFeesApply() {
  //判断是否选中挂号类型
  if (hisSchedulin.value == '') {
    ElMessage({
      message: h('p', { style: 'line-height: 1; font-size: 14px' }, [
        h('span', null, '您还未选择挂号类型'),
        h('i', { style: 'color: teal' }, '请重试'),
      ]),
    })
    return;
  }
  // 判断是否选中挂号的科室
  if (selectedRowInfo.value == null) {
    ElMessage({
      message: h('p', { style: 'line-height: 1; font-size: 14px' }, [
        h('span', null, '您还未选择科室'),
        h('i', { style: 'color: teal' }, '请重试'),
      ]),
    })
    return;
  }
  let formData2=ref({
    patientId:formData.value.partiaid,
    name:formData.value.partialname

  })
  //封装成一个对象
  let requestData = {
        formData: formData.value,
        dept: selectedRowInfo.value,
        hisSchedulingMoery: hisSchedulingMoery.value,
        hisSchedulin:hisSchedulin.value
    };
  //发送http请求
  http.post("/registration/addRegistration", requestData).then((res)=>{

      ElMessage({
    message: '挂号成功',
    type: 'success',
  })
    


  }).catch((res)=>{

  ElMessage.error('挂号失败请重试')

  }).finally(()=>{
    //调用分页查询的方法
    selectedRowInfo.value=null;
    //获取表格信息
  getPageDept(PageNum.value, PageSize.value, value2.value, value3.value, value4.value, date2.value,hisSchedulin.value);

  })
  
}
// 表单数据
const formData = ref({
  patientId: '',
  idCard: '',
  name: '',
  phone: '',
  sex: '',
  birthday: '',
  partialage: '',
  address: ''
});

// 表单引用
const formRef = ref(null);

// 验证规则
const rules = ref({
  partialID: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' }
  ],
  partialname: [
    { required: true, message: '请输入患者信息', trigger: 'blur' }
  ],
  partialphone: [
    { required: true, message: '请输入患者电话', trigger: 'blur' }
  ],
  partialsex: [
    { required: true, message: '请选择患者性别', trigger: 'change' }
  ],
  partialage: [
    { required: true, message: '请输入患者年龄', trigger: 'blur' }
  ],
  partialaddres: [
    { required: true, message: '请输入地址信息', trigger: 'blur' }
  ]
});

// 根据出生日期计算年龄
function setAge() {
  const birthDate = new Date(formData.value.birthday);
  if (isNaN(birthDate.getTime())) {
    ElMessage.error('请输入有效的出生日期');
    return;
  }
  const currentDate = new Date();
  let age = currentDate.getFullYear() - birthDate.getFullYear();
  const monthDiff = currentDate.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && currentDate.getDate() < birthDate.getDate())) {
    age--;
  }
  formData.value.partialage = age.toString();
  ElMessage.success(`计算出的年龄为: ${age}`);
}
</script>

<style scoped>
.margin-radio {
  margin: 22PX;
}

.login {
  margin: auto;
  text-align: center;
  margin-top: 20px;
  box-shadow: 5px 5px 10px 5px #cccccc;
  User-select: none;
  /**设置该元素不可被选中 */
}

.container {
  padding: 20px;
  font-family: Arial, sans-serif;
}

.nav-bar {
  margin-bottom: 20px;
}

.serial-number {
  font-family: monospace;
  margin-bottom: 10px;
}

.rename-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.label {
  white-space: nowrap;
}

.table-nav {
  display: flex;
  gap: 10px;
}

.user-auth {
  display: flex;
  gap: 20px;
}

.user-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  margin-bottom: 20px;
}

.list-item {
  display: flex;
  align-items: center;
}

.list-label {
  min-width: 120px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
}

/*  */
.idcard-section {
  margin: 15px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.result-box {
  margin-top: 10px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-tag {
  margin-left: 10px;
  letter-spacing: 2px;
}

.clinic-selector {
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 4px;
  display: inline-block;
}

.clinic-selector2 {
  padding: 8px 12px;
  border-radius: 4px;
  display: inline-block;
}

:deep(.compact-radio-group) {
  display: flex;
  gap: 1px;
}

:deep(.el-radio-button) {
  --el-radio-button-checked-bg-color: #ffffff;
  --el-radio-button-checked-border-color: #409eff;
  --el-radio-button-checked-text-color: #409eff;
}

:deep(.el-radio-button__inner) {
  padding: 8px 15px;
  border-radius: 0;
  border-left: 1px solid #dcdfe6;
  font-size: 14px;
  color: #606266;
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px 0 0 4px;
  border-left: 1px solid #dcdfe6;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0 4px 4px 0;
}

:deep(.el-radio-button.is-active .el-radio-button__inner) {
  box-shadow: none;
  border-color: #409eff;
  background: linear-gradient(0deg, #ecf5ff, #ffffff);
}

/* 覆盖默认的选中行样式 */
.el-table__row--current {
  background-color: #e0f7fa; /* 可自定义背景颜色 */
}

/* 自定义选中行样式 */
.selected-row {
  background-color: #e0f7fa;
  color: #1976d2; /* 可自定义文本颜色 */
}
</style>    